package com.yyfax.infrastructure.upgrade;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.lang.ref.WeakReference;

/**
 * Created by HenryZhang on 2016/11/23.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public abstract class CompareLocalRemoteTask extends DownloadIfModifiedTask {
	private static final String SP_VER_TIMESTAMP = "ver_timestamp";
	private static final String SP_VER_INFO = "ver_info";

	protected WeakReference<Context> mContext;

	public CompareLocalRemoteTask(Context ctx) {
		mContext = new WeakReference<>(ctx);
	}

    @Override
    protected long getLocalLastModifiedTime() {
		Context ctx = mContext.get();
		if (ctx != null) {
			final SharedPreferences sp = ResourceUtil.getGlobalSharedPreferences(ctx);
			return sp.getLong(SP_VER_TIMESTAMP, 0);
		}
		return 0;
    }

    @Override
    protected Object onDownloadInfo(NetworkPorter.DownloadInfo downloadInfo) {
        Object ret;
        if (downloadInfo != null) {
	        // Download failed
            if (downloadInfo.content == null) {
                ret = parseLocalContent();
            }
            // Download successfully
            else {
                ret = parseContent(downloadInfo.content);
                if (ret != null) {
                    // save valid downloaded content
					Context ctx = mContext.get();
					if (ctx != null) {
						final Editor editor = ResourceUtil.getGlobalSharedPreferencesEditor(ctx);
						editor.putLong(SP_VER_TIMESTAMP, downloadInfo.modifiedTime);
						editor.putString(SP_VER_INFO, downloadInfo.content);
						editor.commit();
					}
                } else {
                    // parse failed
                    ret = parseLocalContent();
                }
            }
        }
        else {
            ret = parseLocalContent();
        }
        return ret;
    }

    private Object parseLocalContent() {
        final String content = getLocalContent();
        return parseContent(content);
    }

    protected String getLocalContent() {
		Context ctx = mContext.get();
		if (ctx != null) {
			final SharedPreferences sp = ResourceUtil.getGlobalSharedPreferences(ctx);
			return sp.getString(SP_VER_INFO, null);
		}
		return null;
    }

    protected abstract Object parseContent(String content);
}
